package org.jeecg.modules.order.monitor;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.dto.message.BusTemplateMessageDTO;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SysAnnmentTypeEnum;
import org.jeecg.modules.coupon.controller.MyCouponController;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.service.ICouponOrderService;
import org.jeecg.modules.coupon.service.ICouponService;
import org.jeecg.modules.coupon.service.IMyCouponService;
import org.jeecg.modules.goodsorder.entity.GoodsOrder;
import org.jeecg.modules.goodsorder.service.IGoodsOrderService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.order.service.IOrderService;
import org.jeecg.modules.system.entity.SysThirdAccount;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysThirdAccountService;
import org.jeecg.modules.system.util.DateUtil;
import org.jeecg.modules.voucher.entity.Voucher;
import org.jeecg.modules.voucher.service.IVoucherService;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecg.modules.zixishi.service.ISeatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class OrderMonitor extends KeyExpirationEventMessageListener {

    @Autowired
    private ISysThirdAccountService sysThirdAccountService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IVoucherService voucherService;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private ISeatService seatService;
    @Autowired
    private ISysBaseAPI sysBaseApi;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IMyCouponService myCouponService;
    @Autowired
    private ICouponOrderService couponOrderService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IGoodsOrderService goodsOrderService;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private MyCouponController myCouponController;

    public OrderMonitor(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {

        if(StringUtils.startsWith(message.toString(),"goodsorder:quxiao")){
            String goodsOrderNum = StringUtils.substringAfter(message.toString(),"goodsorder:quxiao:");
            GoodsOrder goodsOrder = goodsOrderService.getOne(new LambdaQueryWrapper<GoodsOrder>()
                    .eq(GoodsOrder::getOrderNum, goodsOrderNum)
                    .eq(GoodsOrder::getOrderStatus,"0")
            );
            if(null != goodsOrder){
                goodsOrder.setOrderStatus("4");
                goodsOrderService.updateById(goodsOrder);
                String voucherId = goodsOrder.getVoucherId();
                if(StringUtils.isNotBlank(voucherId)){
                    Voucher voucher = voucherService.getById(voucherId);
                    if(null != voucher){
                        voucher.setUseStatus(0);
                        voucherService.updateById(voucher);
                    }
                }
            }
        }else if(StringUtils.startsWith(message.toString(),"voucher:end")){
            String voucherId = StringUtils.substringAfter(message.toString(),"voucher:end:");
            Voucher voucher = voucherService.getById(voucherId);
            if(null != voucher && StringUtils.equals("0","" + voucher.getUseStatus())){
                voucher.setUseStatus(2);
                voucherService.updateById(voucher);
            }
        }else if(StringUtils.startsWith(message.toString(),"mycoupon:end")){
            String myCouponId = StringUtils.substringAfter(message.toString(),"mycoupon:end:");
            MyCoupon myCoupon = myCouponService.getById(myCouponId);
            if(null != myCoupon){
                if(StringUtils.equals(myCoupon.getUseStatus().toString(),"0")) {
                    if(StringUtils.isNotBlank(myCoupon.getReceiptCode())){
                        myCoupon.setUseStatus(3);
                        myCouponService.updateById(myCoupon);
                    }else {
                        myCoupon.setUseStatus(2);
                        myCouponService.updateById(myCoupon);
                        couponOrderService.backMoney(myCoupon.getOrderId());
                    }
                }else if(StringUtils.equals(myCoupon.getUseStatus().toString(),"1")){
                    myCoupon.setUseStatus(3);
                    myCouponService.updateById(myCoupon);
                }
            }
        } else if(StringUtils.startsWith(message.toString(),"orderseat:quxiao")){
            String orderNum = StringUtils.substringAfter(message.toString(),"orderseat:quxiao:");
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum,orderNum));
            if(order!=null && StringUtils.equals("0",order.getOrderStatus())){
                order.setOrderStatus("4");
                orderService.updateById(order);

                String voucherId = order.getVoucherId();
                if(StringUtils.isNotBlank(voucherId)){
                    Voucher voucher = voucherService.getById(order.getVoucherId());
                    voucher.setUseStatus(0);
                    voucherService.updateById(voucher);
                }

//                Map<String, String> templateParam = new HashMap<String,String>(){{
//                    put("orderNum",order.getOrderNum());
//                    put("orderName",order.getOrderName());
//                    put("info","预约人:" + order.getUname() + ",电话:" + order.getUphone());
//                }};
//
//                List<DictModel> configs = sysDictService.getDictItems("msg_receiver");
//                Set<String> adminVals = new HashSet<>();
//                if (null != configs && configs.size() > 0) {
//
//                    for (DictModel dictModel : configs) {
//                        adminVals.add(dictModel.getValue());
//                    }
//                }
//                TemplateMessageDTO message1 = new TemplateMessageDTO("admin",CollectionUtil.join(adminVals, ","),"订单取消通知",templateParam,  "order_cancel");
//                sysBaseApi.sendTemplateAnnouncement(message1);

            }
        }else if(StringUtils.startsWith(message.toString(),"orderseat:start")){
            String orderNum = StringUtils.substringAfter(message.toString(),"orderseat:start:");
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum,orderNum));
            if(order!=null && StringUtils.equals("1",order.getOrderStatus())){
                order.setOrderStatus("2");
                orderService.updateById(order);
                int minutes = DateUtil.minuteDiff(new Date(),order.getEndTime());
                minutes = minutes>0?minutes:1;
                if(minutes>10) {
                    redisUtil.set("orderseat:xudan:" + order.getOrderNum(), "", 60 * (minutes - 10));
                }
                redisUtil.set("orderseat:end:" + order.getOrderNum(), "", 60*(minutes));
                SysThirdAccount thirdAccount = sysThirdAccountService.getOneBySysUserId(order.getSysUserId(),null);
                try {
                    wxMaService.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                            .toUser(thirdAccount.getThirdUserId())
                            .templateId("YlzZd0O0AX2aPZTEQrf-FsWmrSFFXc5b3F6NsxLTjJ4")
                            .data(new ArrayList<WxMaSubscribeMessage.MsgData>(){{
                                add(new WxMaSubscribeMessage.MsgData("character_string1",order.getOrderNum()));
                                add(new WxMaSubscribeMessage.MsgData("time8",new SimpleDateFormat("MM-dd HH:mm").format(order.getStartTime())));
                                add(new WxMaSubscribeMessage.MsgData("thing6",order.getOrderName()));
                                add(new WxMaSubscribeMessage.MsgData("thing5","您预约的订单已经开始"));
                            }})
                            .page("/pages/order/index")
                            .build());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if(StringUtils.startsWith(message.toString(),"orderseat:xudan")){
            String orderNum = StringUtils.substringAfter(message.toString(),"orderseat:xudan:");
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum,orderNum));
            if(order!=null && StringUtils.equals("2",order.getOrderStatus())){
                SysThirdAccount thirdAccount = sysThirdAccountService.getOneBySysUserId(order.getSysUserId(),null);
                try {
                    wxMaService.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                            .toUser(thirdAccount.getThirdUserId())
                            .templateId("OSjmgHmhxfYJilyrtEd3OIYce9Qdk1nkKR8zlyc3nbs")
                            .data(new ArrayList<WxMaSubscribeMessage.MsgData>(){{
                                add(new WxMaSubscribeMessage.MsgData("character_string5",order.getOrderNum()));
                                add(new WxMaSubscribeMessage.MsgData("phrase6","即将到期"));
                                add(new WxMaSubscribeMessage.MsgData("thing4","您的订单将在10分钟之后结束"));
                            }})
                            .page("/pages/order/index")
                            .build());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if(StringUtils.startsWith(message.toString(),"orderseat:end")) {
            String orderNum = StringUtils.substringAfter(message.toString(), "orderseat:end:");
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum, orderNum));
            if (order != null && StringUtils.equals("2",order.getOrderStatus())) {
                order.setOrderStatus("3");
                orderService.updateById(order);

                MPJLambdaWrapper<Seat> wrapper = new MPJLambdaWrapper<Seat>()
                        .selectAll(Seat.class)
                        .selectAs(Quyu::getName,Seat::getQuyuName)
                        .leftJoin(Quyu.class, Quyu::getId,Seat::getQuyuId)
                                .eq(Seat::getId,order.getSeatId());
                Seat seat = seatService.getOne(wrapper);

                Map<String, String> templateParam = new HashMap<String,String>(){{
                    put("orderNum",order.getOrderNum());
                    put("orderName",order.getOrderName());
                    put("endTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getEndTime()));
                    put("seat",seat.getQuyuName()+ ">" +seat.getName());
                }};

                List<DictModel> configs = sysDictService.getDictItems("msg_receiver");
                Set<String> adminVals = new HashSet<>();
                if (null != configs && configs.size() > 0) {

                    for (DictModel dictModel : configs) {
                        adminVals.add(dictModel.getValue());
                    }
                }
                TemplateMessageDTO message1 = new TemplateMessageDTO("admin",CollectionUtil.join(adminVals,","),"订单结束通知",templateParam,  "order_finished");
                sysBaseApi.sendTemplateAnnouncement(message1);

                try {
                    List<DictModel> configs1 = sysDictService.getDictItems("goodorder_receiver");
                    Set<String> adminVals1 = new HashSet<>();
                    if (null != configs1 && configs1.size() > 0) {

                        for (DictModel dictModel : configs1) {
                            adminVals1.add(dictModel.getValue());
                        }
                    }
                    //公众号模板消息
                    //5qNrTu0mk1bbLOxz05dmbWzQ37UrPHlNM0BW3T7oalE
                    List<WxMpTemplateData> data = new ArrayList<>();
                    data.add(new WxMpTemplateData("character_string6", order.getOrderNum()));//订单编号
                    data.add(new WxMpTemplateData("thing8", order.getOrderName())); //服务类型
                    data.add(new WxMpTemplateData("thing22", seat.getQuyuName()+ ">" +seat.getName())); //下单时间
                    data.add(new WxMpTemplateData("time9", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getStartTime()))); //用户名
                    data.add(new WxMpTemplateData("time10", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getEndTime()))); //用户名
                    if(CollectionUtil.isNotEmpty(adminVals1)){
                        for (String adminVal : adminVals1) {
                            wxMpService.getTemplateMsgService().sendTemplateMsg(WxMpTemplateMessage.builder()
                                    .toUser(adminVal)
                                    .templateId("9u-W7QjAGQEuLEG7sK_nsTefwnbFBWMQonOJvckNvs4")
                                    .url("")
                                    .data(data)
                                    .build());
                        }
                    }
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }
        }
    }
}
